import React, { Component } from 'react'
import { withFormik, Form, Field, ErrorMessage } from 'formik'
import { Toast } from 'antd-mobile'
import { Link } from 'react-router-dom'
import API from '../../utils/api'
// 导入Yup
import * as Yup from 'yup'
import NavHeader from '../../components/NavHeader'
import './index.sass'
// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/
class Registe extends Component {
  render() {
    return (
      <div className="registe">
        <NavHeader className="nav-bar_white">账号登录</NavHeader>
        <div className="form-box">
          <Form>
            <Field className="input" name="username" placeholder="请输入账号" />
            <ErrorMessage className="error" name="username" component="div" />
            <Field className="input" name="password" placeholder="请输入密码" type="password" />
            <ErrorMessage className="error" name="password" component="div" />
            <Field className="input" name="againPassword" placeholder="请再次输入密码" type="password" />
            <ErrorMessage className="error" name="againPassword" component="div" />
            <div className="submit">
              <button type="submit">
                注册
              </button>
            </div>
          </Form>
        </div>
        <div className="to-registe">
          <Link to="/registe">还没有账号，去注册~</Link>
        </div>
      </div>
    )
  }
}
Registe = withFormik({
  mapPropsToValues: () => ({ username: '', password: '',againPassword:'' }),
  validationSchema: Yup.object().shape({
    username: Yup.string().required('账号为必填项').matches(REG_UNAME, '长度为5到8位，只能出现数字、字母、下划线'),
    password: Yup.string().required('密码为必填项').matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
    againPassword:Yup.string().required('确认密码为必填项').matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
  }),
  validate: values => {
    const errors = {}
    const {password, againPassword} = values
   if(password!==againPassword){
     errors.againPassword='两次密码不一致'
   }
    return errors
  },

  handleSubmit: async (values, { props }) => {
    let { username, password } = values
    let res = await API.post('/user/registered', { username, password })
    const { status,  description } = res
    if (status === 200) {
      Toast.success('注册成功', 2, null, false)
      setTimeout(()=>{
        props.history.goBack()
      },500)
    } else {
      // 登录失败
      Toast.info(description, 2, null, false)
    }
  }

})(Registe)
export default Registe
